//
//  CYYSDetailVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/28.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYYSDetailVC.h"
#import "CYYSDefaultPersonsView.h"
#import "CYDefaultRecordCell.h"
#import "CYDefaultRecordAO.h"
#import "CYABTool.h"
#import "CYEscape.h"
#import "CYCreditDetailTVController.h"
#import "MBProgressHUD+MJ.h"
#import "CYCreditDetailVC.h"
#import "UIInfomationView.h"
#import "CYNavigationVController.h"
#import "LEAlertView+LE.h"
#import "CYYSFilterView.h"
#import "MJRefresh.h"
#import "LEDIYFooter.h"

static CGFloat _sectionH = 50;

@interface CYYSDetailVC ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *defts;
@property(nonatomic, weak) UITableView *tableview;
//筛选
@property(nonatomic, strong) NSString *city;
@property(nonatomic, assign) CYSex sex;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL isFilter;
@end

@implementation CYYSDetailVC

- (NSMutableArray *)defts {
    if (!_defts) {
        _defts = [NSMutableArray array];
    }
    return _defts;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    [self setupItem];
    [self setExtraCellLineHidden];
}

- (void)setupView {
    CYYSDefaultPersonsView *view = [CYYSDefaultPersonsView ysDefaultPersonsView];
    view.frame = self.view.frame;
    view.tableView.delegate = self;
    view.tableView.dataSource = self;
    self.tableview = view.tableView;
    [self.view addSubview:view];
    [self setupPersonWithView:view];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)setupItem {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(filterBtn:)];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)setupPersonWithView:(CYYSDefaultPersonsView *)view {
    CYPerson *person = self.person;
    if (person.name) {
        view.nameLabel.text = [NSString stringWithFormat:@"姓名：%@", person.name];
    }
    if (person.phone) {
        view.phoneLabel.text = [NSString stringWithFormat:@"电话：%@", person.phone];
    }
    if (person.person.thumbnail) {
        [view.headImageView setImage:person.person.thumbnail];
    }
    view.headImageView.layer.cornerRadius = 30.f;
    view.headImageView.layer.masksToBounds = YES;
    //从服务器加载数据
//    [MBProgressHUD showMessage:@"加载中" toView:view.tableView];
//    [self loadData];
    //集成刷新控件
    [self setupRefresh];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh {
    //首次加载
    [MBProgressHUD showMessage:nil toView:self.view];
    [self filterData:NO];
    CYWeakObject(weakself, self);
    LEDIYFooter *footer = [LEDIYFooter footerWithRefreshingBlock:^{
        [weakself filterData:weakself.isFilter];
    }];
    self.tableview.mj_footer = footer;
    footer.refreshingTitleHidden = YES;
}

#pragma mark - table delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.defts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CYDefaultRecordCell *cell = [CYDefaultRecordCell cellWithTableView:tableView];
    cell.defr = self.defts[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CYDefaultRecordAO *defr = self.defts[indexPath.row];
    //            CYCreditDetailTVController *credetail = [[CYCreditDetailTVController alloc] init];
    CYCreditDetailVC *credetail = [[CYCreditDetailVC alloc] init];
    defr.pushTag = 1;
    credetail.defr = defr;
    [self.navigationController pushViewController:credetail animated:YES];
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return [NSString stringWithFormat:@"共有%lu条数据", (unsigned long)self.defts.count];
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGFloat height = _sectionH;
    CGFloat labelH = 15;
    CGFloat margin = 4;
    //添加显示view
    UIView *view = [[UIView alloc] initForAutoLayout];
    view.backgroundColor = self.view.backgroundColor;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, margin, self.view.width, labelH)];
    [view addSubview:label];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor grayColor];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(16, height - labelH - margin, self.view.width, labelH)];
    [view addSubview:label1];
    label1.font = [UIFont systemFontOfSize:14];
    label1.textColor = [UIColor grayColor];
    label1.text = @"一个都不认识？取消疑似";
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(175, height - labelH - margin, 50, labelH)];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [view addSubview:btn];
    [btn setBackgroundColor:CYNaviThemeColor];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(cancelDef) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, height - 1, self.view.width, 1)];
    [view addSubview:line];
    line.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    if (self.person.count) {
        label.text = [NSString stringWithFormat:@"以下是关于%@的%lu条疑似记录,请认真核实并确认。", self.person.name, (unsigned long)self.person.count];
    } else {
        label.text = [NSString stringWithFormat:@"以下是关于%@的%lu条疑似记录,请认真核实并确认。", self.person.name, (unsigned long)self.defts.count];
    }
    //设置标题
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 105;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _sectionH;
}

#pragma mark -
/**
 *  取消疑似
 */
- (void)cancelDef {
    [UIInfomationView showAlertViewWithTitle:CYStringFormat(@"确定要将%@从疑似失信人中移除吗？", self.person.name) message:@"移除后该联系人将不会再出现在疑似失信人列表中" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
/**
 *  疑似筛选
 */
- (void)filterBtn:(UIBarButtonItem *)item {
    item.enabled = NO;
    CYYSFilterView *view = [CYYSFilterView loadFromNibUsingClassName];
    view.backgroundColor = [UIColor clearColor];
    view.controller = self;
    CYWeakObject(weakself, self);
    [LEAlertView showAlertViewWithButton:@"筛选" cancelButton:@"取消" customView:view showInView:self.view clickAtIndex:^(NSInteger index) {
        if (index == 1) {
            weakself.city = view.selectedCity;
            weakself.sex = view.selectedSex;
            weakself.page = 0;
            [weakself.defts removeAllObjects];
            [MBProgressHUD showMessage:nil toView:self.view];
            [weakself filterData:YES];
        }
        item.enabled = YES;
    }];
}
/**
 *  服务器加载数据，现改为统一使用filterData:加载
 */
- (void)loadData {
    [CYABTool defaultRecordsByNameWithParams:@{@"condition": self.person.name, @"page": @"0"} success:^(NSArray *defrs) {
        [MBProgressHUD hideHUDForView:self.tableview animated:YES];
        [self.defts addObjectsFromArray:defrs];
        [self.tableview reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.tableview animated:YES];
        [MBProgressHUD showError:@"网络连接失败" toView:self.view];
        CYLog(@"根据姓名加载失信人失败：%@", error);
    }];
}
/**
 *  加载服务器疑似筛选
 */
- (void)filterData:(BOOL)isFilter {
    NSDictionary *param = nil;
    if (self.city) {
        param = @{@"name": self.person.name, @"city": self.city, @"sex": @(self.sex), @"page": @(self.page)};
    } else if (isFilter) {
        param = @{@"name": self.person.name, @"sex": @(self.sex), @"page": @(self.page)};
    } else {
        param = @{@"name": self.person.name, @"page": @(self.page)};
    }
    self.isFilter = isFilter;
    [CYABTool getDefaultRecordsByCityAndSexWithParam:param success:^(NSArray *defrs) {
        [MBProgressHUD hideHUDForView:self.view];
        if (defrs.count) {
            [self.defts addObjectsFromArray:defrs];
            self.page++;
            [self.tableview.mj_footer endRefreshing];
        } else {
            [self.tableview.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableview reloadData];
    } failure:^(NSString *message, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableview.mj_footer endRefreshing];
        if (message) {
            [MBProgressHUD showError:message];
        }
    }];
}
/**
 *  去除多余cell分割线，在tableView初始化的时候调用该方法
 *
 *  @param tableView
 */
- (void)setExtraCellLineHidden {
    UIView *view =[[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [self.tableview setTableFooterView:view];
}

- (void)dealloc {
    CYLog(@"疑似失信人列表销毁");
    [self.tableview.mj_footer endRefreshing];
}
@end
